package org.example.sse.controller;

import com.alibaba.fastjson.JSONObject;
import org.example.sse.config.SseEmitterUTF8;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class SseController {
    private final ExecutorService nonBlockingService = Executors.newCachedThreadPool();

    @GetMapping(value = "/sse")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitterUTF8(60000L);
        String[] split = ("冷笑话：为什么Java程序员讨厌天气应用？ ——因为每次调用 getSun() 都返回 null …… " +
                "（冷笑话解析： NullPointerException 是Java程序员最常遇到的错误，而天气应用如果返回 null 表示“没太阳”，程序员还得处理异常，冷到瑟瑟发抖）").split("[：？， ]");
        nonBlockingService.execute(() -> {
            try {
                for (int i = 0; i < split.length; i++) {
                    JSONObject object = new JSONObject();
                    object.put("id", UUID.randomUUID().toString());
                    object.put("content", split[i]);
                    SseEmitter.SseEventBuilder event = SseEmitter.event()
                            .data(object.toJSONString(), new MediaType(MediaType.TEXT_PLAIN))
                            .id(String.valueOf(i))
                            .name("" + i);
                    emitter.send(event);
                    Thread.sleep(1000);
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
}